package com.jiusit.onePurchase.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.jfinal.ApiController;
import com.jiusit.common.utils.StringUtil;
import com.jiusit.onePurchase.interceptor.UserInterceptor;
import com.jiusit.onePurchase.model.PurchaseAdvertisement;
import com.jiusit.onePurchase.model.PurchaseCommodity;
import com.jiusit.onePurchase.model.PurchaseCommodityBuy;
import com.jiusit.onePurchase.model.PurchaseCommodityCar;
import com.jiusit.onePurchase.model.PurchaseCommodityCollect;
import com.jiusit.onePurchase.model.PurchaseCommodityContent;
import com.jiusit.onePurchase.model.PurchaseCommodityRecord;
import com.jiusit.onePurchase.model.PurchaseCommodityVersion;
import com.jiusit.onePurchase.model.PurchaseSentAddress;
import com.jiusit.onePurchase.model.PurchaseTicket;
import com.jiusit.onePurchase.model.PurchaseTicketRandom;
import com.jiusit.onePurchase.model.PurchaseUserTicket;
import com.jiusit.onePurchase.model.PurchaseVersionExt;
import com.jiusit.onePurchase.model.OnePurchaseUser;
import com.jiusit.onePurchase.model.PurchaseCommodityPay;
import com.jiusit.onePurchase.model.TradeMarketShare;
import com.jiusit.onePurchase.model.WbVar;
import com.jiusit.onePurchase.service.StoredProcedureService;
@ControllerBind(controllerKey="/home",viewPath="/pages")
@Before(UserInterceptor.class)


/*
 * 首页
 * */
public class HomeController extends ApiController{
	private static final Logger log = Logger
			.getLogger(HomeController.class);

	@Override
	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();

		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setAppId(PropKit.get("client_ID"));
		ac.setAppSecret(PropKit.get("client_SERCRET"));
		
		
		/**
		 * 是否对消息进行加密，对应于微信平台的消息加解密方式： 1：true进行加密且必须配置 encodingAesKey
		 * 2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey",
				"setting it in config file"));
		return ac;
	}
   //首页
	
	public void homePage(){
		String from_user=getCookie("wbUid");
		String commodity_id=getPara("id");
		String agent_num=getPara("agent_num");
		String agent_id="";
		if(!StringUtil.isEmpty(agent_num)){
			String[] agentNums=agent_num.split(",");
			agent_id=agentNums[0];
			if(agentNums.length>=2){
			if(StringUtil.isEmpty(commodity_id)){
				commodity_id=agentNums[1];
			}
			}
		}
		if(!StringUtil.isEmpty(from_user)){
			if(!StringUtil.isEmpty(commodity_id)){
				PurchaseCommodity commodity=PurchaseCommodity.dao.findById(commodity_id);
                if(commodity != null ){
				redirect("/home/commodityDetail?id="+commodity_id);
				return;
				}else{
					redirect("/home/homePage");
					return;
				}
			}else{
		OnePurchaseUser user=OnePurchaseUser.dao.findFirst("select * from purchase_users where wx_id='"+from_user+"'");
		List <PurchaseAdvertisement> topAdvertisementList=PurchaseAdvertisement.dao.find("select * from purchase_advertisement where top_show='1' and is_enable='1' order by sort ");
		PurchaseAdvertisement advertisement=PurchaseAdvertisement.dao.findFirst("select * from purchase_advertisement where top_show='0' and is_enable='1' order by sort");
		Page <PurchaseCommodity> commodityPage=PurchaseCommodity.dao.paginate(1,16,"select a.* "," from purchase_commodity a where a.commodity_type='01' and a.commodity_status='01' and (select count(*) from purchase_commodity_version where commodity_id=a.id and version_stock > 0 ) >0 order by a.sort");
		Page <PurchaseCommodity> purchasePage=PurchaseCommodity.dao.paginate(1,10,"select b.commodity_name,b.commodity_logo,a.total_count,a.surplus_count,a.commodity_id,a.id,(a.total_count-a.surplus_count)*100/a.total_count as 'per' ","from purchase_time_slot a left join purchase_commodity b on b.id=a.commodity_id  where b.commodity_type='02' and b.commodity_status='01' and a.is_over='0' and status ='01' and NOW() BETWEEN a.begin_date and a.end_date  order by a.sort, surplus_count ");
		setAttr("topAdvertisementList", topAdvertisementList);
		setAttr("advertisement", advertisement);
		setAttr("commodityList", commodityPage.getList());
		setAttr("commodityTotalPage", commodityPage.getTotalPage());
		setAttr("commodityPageNumber", commodityPage.getPageNumber());
		setAttr("purchaseList", purchasePage.getList());
		setAttr("purchaseTotalPage", purchasePage.getTotalPage());
		setAttr("purchasePageNumber", purchasePage.getPageNumber());
		setAttr("login_num", user.getInt("login_num"));
		setAttr("server_uri", PropKit.get("server_uri"));
		render("index.html");
			}
		}else{
			String url=getRequest().getRequestURI();
			if(!StringUtil.isEmpty(agent_num)){
				setAttr("url", url.substring(url.indexOf("b")+1, url.length())+"?agent_num="+agent_num);
			}else{
				setAttr("url", url.substring(url.indexOf("b")+1, url.length()));
			}
			
			render("error.html");
		}
	}
	// 跳转到领取卡卷页面
		public void forwardTicket() {
			String from_user=getCookie("wbUid");
			OnePurchaseUser user=OnePurchaseUser.dao.findFirst("select * from purchase_users where wx_id='"+from_user+"'");
			if (user != null) {
				WbVar wv = WbVar.dao.findFirst("select * from wb_var where  VAR_NAME='ticket_id' ");
				if(wv!=null){
					PurchaseTicketRandom ptr = PurchaseTicketRandom.dao.findFirst("select * from purchase_ticket_random where ticket_id='"+wv.getStr("VAR_VALUE")+"' and ticket_status='01' AND ticket_type='01' AND TO_DAYS(NOW()) BETWEEN TO_DAYS(begin_date) AND TO_DAYS(end_date) ");
					setAttr("ptr", ptr);
					PurchaseTicket pt = PurchaseTicket.dao
							.findFirst("SELECT a.*,b.key_value AS 'card_type_s' FROM purchase_ticket a LEFT JOIN wb_key b ON a.card_type=b.key_name WHERE a.id='"+wv.getStr("VAR_VALUE")+"' AND a.STATUS='1' AND a.ticket_type='01' AND b.key_type='purchase_ticket.card_type' AND NOT EXISTS (SELECT * FROM purchase_user_ticket WHERE wx_id='"+from_user+"' AND ticket_id='"+wv.getStr("VAR_VALUE")+"' )");
					setAttr("pt", pt);
					PurchaseUserTicket purchaseUserTicket = PurchaseUserTicket.dao
							.findFirst("SELECT a.*,b.key_value AS 'card_type_s' FROM purchase_user_ticket a LEFT JOIN wb_key b ON a.card_type=b.key_name WHERE a.ticket_id='"+wv.getStr("VAR_VALUE")+"' and a.wx_id='"+from_user+"' ");
					setAttr("purchaseUserTicket", purchaseUserTicket);
				}
				render("ticket_page.html");
			}else{
				String url=getRequest().getRequestURI();
				setAttr("url", url.substring(url.indexOf("b")+1, url.length()));
				render("error.html");
			}
		}
		// 用户领取卡卷
		public void toTicket() {
			Map map=new HashMap();
			String from_user=getCookie("wbUid");
			String ticket_id = getPara("ticket_id");
			OnePurchaseUser user=OnePurchaseUser.dao.findFirst("select * from purchase_users where wx_id='"+from_user+"'");
			if (user != null) {
				PurchaseTicket pt = PurchaseTicket.dao.findFirst("select * from purchase_ticket where id='"+ticket_id+"' AND TO_DAYS(NOW()) BETWEEN TO_DAYS(begin_date) AND TO_DAYS(end_date)");
				if(pt!=null){
					PurchaseTicketRandom ptr = PurchaseTicketRandom.dao.findFirst("select * from purchase_ticket_random where ticket_status='01' and ticket_id='"+ticket_id+"' AND TO_DAYS(NOW()) BETWEEN TO_DAYS(begin_date) AND TO_DAYS(end_date) ORDER BY rand() limit 0,1 ");
					if(ptr!=null){
						  int result=StoredProcedureService.trackresult(ptr.getStr("id"),from_user,user.getStr("id"),user.getStr("nick_name"),new BigDecimal("0"),"01",2,3,"01");
						if(result >= 1){
							map.put("code", 0);
							map.put("msg", "领取成功");
						}else{
							map.put("code", 0);
							map.put("msg", "系统繁忙，稍后再试");
						}
					}else{
						map.put("code", -1);
						map.put("msg", "卡券已领完");
					}
				}else{
					map.put("code", -1);
					map.put("msg", "卡券已过期");
				}
				renderJson(map);
			}else{
				String url=getRequest().getRequestURI();
				setAttr("url", url.substring(url.indexOf("b")+1, url.length()));
				render("error.html");
			}
		}
	//普通商品分页
	@Clear
   public void commodityListPage(){
	   String page=getPara("page");
	   if(StringUtil.isEmpty(page)){
		   page="1";
	   }
		Page <PurchaseCommodity> commodityPage=PurchaseCommodity.dao.paginate(Integer.parseInt(page),10,"select * ","from purchase_commodity where commodity_type='01' and commodity_status='01' order by sort");
		setAttr("commodityPage", commodityPage);
		setAttr("server_uri", PropKit.get("server_uri"));
		renderJson(commodityPage);
	}
	 //普通商品明细
	   public void commodityDetail(){
			String id=getPara("id"); //商品id
			String agent_num=getPara("agent_num"); //代理商分享code
			String agent_id="";
			if(!StringUtil.isEmpty(agent_num)){
				String[] agentNums=agent_num.split(",");
				agent_id=agentNums[0];
				if(agentNums.length>=2){
				if(StringUtil.isEmpty(id)){
					id=agentNums[1];
				}
				}
			}
			String from_user=getCookie("wbUid");
			if(!StringUtil.isEmpty(from_user)){
				PurchaseCommodity checkCommodity=PurchaseCommodity.dao.findById(id);
				if(checkCommodity != null){
			OnePurchaseUser user=OnePurchaseUser.dao.findFirst("select * from purchase_users where wx_id='"+from_user+"'");
			PurchaseCommodityCollect commodityCollect=PurchaseCommodityCollect.dao.findFirst("select count(*) as 'count' from purchase_commodity_collect where commodity_id='"+id+"' and user_id='"+user.get("id")+"'");
			Map map=new HashMap();
			if(commodityCollect == null ){
				setAttr("count", 0);
			}else{
				setAttr("count", commodityCollect.getLong("count"));
			}
			PurchaseCommodity commodity=PurchaseCommodity.dao.findById(id);
			List<PurchaseCommodityVersion> commodityVersionList=PurchaseCommodityVersion.dao.find("select * from purchase_commodity_version where commodity_id='"+id+"' and version_stock > 0 order by version_sort");
			List<PurchaseVersionExt> versionExtList = new ArrayList<PurchaseVersionExt>();
			if(commodityVersionList.size()>0){
			   versionExtList=PurchaseVersionExt.dao.find("select * from purchase_version_ext where version_id='"+commodityVersionList.get(0).get("id")+"' order by ext_sort");
			   setAttr("version_stock", commodityVersionList.get(0).get("version_stock"));
			}
			Page<PurchaseCommodityContent> commodityContent=PurchaseCommodityContent.dao.paginate(1, 10, "select a.*", " from purchase_commodity_content a  where a.commodity_id='"+id+"'");
			List<PurchaseCommodityContent> commodityContentList=PurchaseCommodityContent.dao.find( "select a.* from purchase_commodity_content a  where a.commodity_id='"+id+"'");
			List<PurchaseCommodityCar> commodityCarlist = PurchaseCommodityCar.dao.find("select * from purchase_commodity_car where user_id = '"+user.getStr("id")+"' and order_type='01' and commodity_type = '01' order by create_date desc ");
			setAttr("commodity", commodity);
			setAttr("commodityVersionList", commodityVersionList);
			setAttr("commodityContentList", commodityContent.getList());
			setAttr("commodityContentTotalPage", commodityContent.getTotalPage());
			setAttr("commodityContentPageNumber", commodityContent.getPageNumber());
			setAttr("total_num", commodityContentList.size());
			setAttr("versionExtList", versionExtList);
			setAttr("car_size", commodityCarlist.size());
			setAttr("server_uri", PropKit.get("server_uri"));
			render("product_detail.html");
				}else{
					redirect("/home/homePage");
				}
			}else{
				String redirect_url="https://api.weibo.com/oauth2/authorize?client_id="
							+ PropKit.get("client_ID")
							+ "&response_type=code&redirect_uri="
							+ PropKit.get("redirect_URI");
				if(!StringUtil.isEmpty(agent_num)){
					redirect_url+="?agent_num="+agent_num;
				}else{
					redirect_url+="?id="+id;
				}
				redirect(redirect_url);
			}
		}
   
   //型号轮播图片切换
	@Clear
   public void changeVersionPic(){
		String id=getPara("id");
		String version_id=getPara("version_id");
		List<PurchaseVersionExt> versionExtList=PurchaseVersionExt.dao.find("select * from purchase_version_ext where version_id='"+version_id+"' order by ext_sort");
		Map map=new HashMap();
		map.put("versionExtList", versionExtList);
		map.put("server_uri", PropKit.get("server_uri"));
		renderJson(map);
	}
   //一元购商品分页
	@Clear
   public void onePurchaseListPage(){
	   String page=getPara("page");
	   if(StringUtil.isEmpty(page)){
		   page="1";
	   }
		Page <PurchaseCommodity> purchasePage=PurchaseCommodity.dao.paginate(Integer.parseInt(page),10,"select b.commodity_name,b.commodity_logo,a.total_count,a.surplus_count,a.commodity_id,a.id,(a.total_count-a.surplus_count)*100/a.total_count as 'per' ","from purchase_time_slot a left join purchase_commodity b on b.id=a.commodity_id  where b.commodity_type='02' and b.commodity_status='01' and a.is_over='0' and status ='01' and NOW() BETWEEN a.begin_date and a.end_date  order by a.sort, surplus_count ");
		setAttr("purchasePage", purchasePage);
		setAttr("server_uri", PropKit.get("server_uri"));
		renderJson(purchasePage);
	}
		 //是否收藏
	    @Clear
		public void isCollect(){
	    	String from_user=getCookie("wbUid");
			String id = getPara("id");
			if(!StringUtil.isEmpty(from_user)){
				OnePurchaseUser user=OnePurchaseUser.dao.findFirst("select * from purchase_users where wx_id='"+from_user+"'");
				PurchaseCommodityCollect commodityCollect=PurchaseCommodityCollect.dao.findFirst("select count(*) as 'count' from purchase_commodity_collect where commodity_id='"+id+"' and user_id='"+user.get("id")+"'");
				Map map=new HashMap();
				map.put("count", commodityCollect.getLong("count"));
				renderJson(map);
			}else{
				String url=getRequest().getRequestURI();
				setAttr("url", url.substring(url.indexOf("b")+1, url.length())+"?id="+id);
				render("error.html");
			}
		}
		
		 //收藏
		public void collectCommodity(){
			String from_user=getCookie("wbUid");
			String id = getPara("id"); //商品id
			String commodity_type = getPara("commodity_type"); //商品类型
			if(!StringUtil.isEmpty(from_user)){
				OnePurchaseUser user=OnePurchaseUser.dao.findFirst("select * from purchase_users where wx_id='"+from_user+"'");
				PurchaseCommodityCollect commodityCollect=PurchaseCommodityCollect.dao.findFirst("select id, count(*) as 'count' from purchase_commodity_collect where commodity_id='"+id+"' and user_id='"+user.get("id")+"'");
				Map map=new HashMap();
				if(commodityCollect.getLong("count") >0){
					PurchaseCommodityCollect.dao.deleteById(commodityCollect.get("id"));
					map.put("code", "1");
					map.put("msg", "成功取消收藏");
					
				}else{
					PurchaseCommodityCollect collect=new PurchaseCommodityCollect().set("id", StringUtil.getUUID())
							.set("commodity_id", id)
							.set("user_id", user.get("id"))
							.set("collect_date", new Date())
							.set("commodity_type", commodity_type)
							.set("create_by", user.get("id"))
							.set("create_name", user.get("nick_name"))
							.set("create_date", new Date())
							.set("update_by", user.get("id"))
							.set("update_name", user.get("nick_name"))
							.set("update_date", new Date())
							.set("remarks","收藏商品")
							;
					collect.save();
					map.put("code", "0");
					map.put("msg", "收藏成功");
				}
				renderJson(map);
			}else{
				String url=getRequest().getRequestURI();
				setAttr("url", url.substring(url.indexOf("b")+1, url.length())+"?id="+id);
				render("error.html");
			}
		}
		
		//浏览
				public void browseCommodity(){
					String id=getPara("id");
					String from_user=getCookie("wbUid");
					String commodity_type=getPara("commodity_type");
					if(!StringUtil.isEmpty(from_user)){
						OnePurchaseUser user=OnePurchaseUser.dao.findFirst("select * from purchase_users where wx_id='"+from_user+"'");
						PurchaseCommodityRecord countRecord=PurchaseCommodityRecord.dao.findFirst("select count(*) as 'count' from purchase_commodity_record where user_id='"+user.get("id")+"'");
						PurchaseCommodityRecord checkRecord=PurchaseCommodityRecord.dao.findFirst("select * from purchase_commodity_record where user_id='"+user.get("id")+"' and commodity_id='"+id+"'");
						if(checkRecord == null){
						PurchaseCommodityRecord commodityRecord=new PurchaseCommodityRecord().set("id", StringUtil.getUUID())
								.set("commodity_id", id)
								.set("user_id", user.get("id"))
								.set("record_date", new Date())
								.set("commodity_type", commodity_type)
								.set("create_by", user.get("id"))
								.set("create_name", user.get("nick_name"))
								.set("create_date", new Date())
								.set("update_by", user.get("id"))
								.set("update_name", user.get("nick_name"))
								.set("update_date", new Date())
								.set("remarks", "商品浏览记录")
								;
						commodityRecord.save();
						}else{
							PurchaseCommodityRecord updateRecord=new PurchaseCommodityRecord().set("id", checkRecord.get("id"))
									.set("record_date", new Date())
									;
							updateRecord.update();
						}
						if(!StringUtil.isEmpty(user.getStr("agent_code"))){
							TradeMarketShare checkMarketShare=TradeMarketShare.dao.findFirst("select * from trade_market_share where agent_id='"
									+user.getStr("agent_code")+"' and commodity_id='"+id+"' ");
							if(checkMarketShare == null ){
								TradeMarketShare marketShare=TradeMarketShare.dao
										.set("id", StringUtil.getUUID())
										.set("agent_id", user.getStr("agent_code"))
										.set("commodity_id", id)
										.set("agent_code", user.getStr("agent_code"))
										.set("access_num", 0)
										.set("create_by", user.getStr("id"))
										.set("create_name", user.getStr("nick_name"))
										.set("create_date", new Date())
										.set("update_by", user.getStr("id"))
										.set("update_name", user.getStr("nick_name"))
										.set("update_date", new Date())
										.set("remarks", "浏览商品");
								marketShare.save();
								
							}else{
								Db.update("update trade_market_share set access_num=access_num+1 where id='"+checkMarketShare.getStr("id")+"'");
							}
							}
						renderNull();
					}else{
						String url=getRequest().getRequestURI();
						setAttr("url", url.substring(url.indexOf("b")+1, url.length())+"?id="+id);
						render("error.html");
					}
				}
				
				//评论分页
				@Clear
			   public void commodityContentPage(){
				   String page=getPara("page");
				   String commodity_id=getPara("commodity_id");
				   if(StringUtil.isEmpty(page)){
					   page="1";
				   }
				   Page<PurchaseCommodityContent> commodityContent=PurchaseCommodityContent.dao.paginate(Integer.parseInt(page), 10, "select a.*", " from purchase_commodity_content a  where a.commodity_id='"+commodity_id+"'");
				    setAttr("commodityPage", commodityContent);
					setAttr("server_uri", PropKit.get("server_uri"));
					renderJson(commodityContent);
				}
				//一元购介绍页
				@Clear
			   public void introduceOnePurchase(){
				   
				   render("rule.html");
				}
				//清除缓存
				@Clear
			   public void clearCookie(){
					setCookie("wbUid", null, 0, "/");
					renderNull();
				}
}
